# -*- coding: utf-8 -*-

"""
 Copyright (C) 2009 Jean Pierre Charalambos. All rights reserved.

 Jean Pierre Charalambos (http://dis.unal.edu.co/profesores/pierre/) is an
 Affiliate Associate Professor of the Faculty of Engineering at National
 University of Colombia (http://www.unal.edu.co/).

 This file is part of maku version 0.2.

 http://code.google.com/p/maku/
 email: jpcharalambosh@unal.edu.co

 This file may be used under the terms of the GNU General Public License 
 versions 2.0 or 3.0 as published by the Free Software Foundation and
 appearing in the COPYING file included in the packaging of this file.

 This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
 WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
"""

import sys
import rsc_rc

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtOpenGL import *
from mainwindow import Ui_MainWindow

class UNLine(QGraphicsItem):
    def __init__(self, a=QPointF(), b=QPointF()):
        """
	UNLine representa la clase de la linea a implementar
	"""
        QGraphicsItem.__init__(self)
        self.p1 = a
        self.p2 = b

    def boundingRect(self):
        penWidth = 1.0
        return QRectF(-10 - penWidth / 2, -10 - penWidth / 2, 20 + penWidth / 2, 20 + penWidth / 2);

    def paint(self, painter, option, widget):
        #la linea se deberia pintar tomando p1 y p2 (que son QPointF) y empleando unicamente el metodo drawPoint de painter (que es del tipo QPainter)
        painter.drawRoundedRect(-10, -10, 20, 20, 5, 5)

class SimpleScene(QGraphicsScene):
    def __init__(self):
        """
        simplescene representa el objeto de alto nivel que manipula la escena. Ver QGraphicsView in Qt4
        """
        QGraphicsScene.__init__(self)
        self.setSceneRect(-300, -300, 600, 600)
        self.setItemIndexMethod(QGraphicsScene.NoIndex)
        #crea accion local:
        self.lineColorAction = QAction("&Line color", self)
        self.lineColorAction.setShortcut("Ctrl+C")
        self.lineColorAction.setStatusTip("Set line color")
        self.connect(self.lineColorAction, SIGNAL("triggered()"), self.setLineColor)
        self.line = QLineF(0,0,1,1)
        self.lineColor = QColor(Qt.black)
        self.flagInteractive = False

    def setLineColor(self):
          color = QColorDialog.getColor(self.lineColor)
          if color.isValid():
              self.lineColor = color

    def mousePressEvent(self, mouseEvent):
        if mouseEvent.button() != Qt.LeftButton:
            return
        #ojo! dibujo interactivo de la linea: la siguiente es la linea que se dibuja mientras se arrastra el mouse, es diferente de la linea definitiva, definida implicitamente en el metodo mouseReleaseEvent
        self.line = QGraphicsLineItem(QLineF(mouseEvent.scenePos(), mouseEvent.scenePos()))
        self.line.setPen( QPen(self.lineColor) )
        self.addItem(self.line)
        self.flagInteractive = True
        QGraphicsScene.mousePressEvent(self, mouseEvent)
        self.initPos = mouseEvent.scenePos()

    def mouseMoveEvent(self, mouseEvent):
        if self.mouseGrabberItem():
            #entonces mueve el objeto seleccionado
            QGraphicsScene.mouseMoveEvent(self, mouseEvent)
        elif self.flagInteractive:
            self.line.setLine(QLineF(self.line.line().p1(), mouseEvent.scenePos()))

    def mouseReleaseEvent(self, mouseEvent):
        if not self.mouseGrabberItem():
            #saca de la escena la linea interactiva
            self.removeItem(self.line)
            item = QGraphicsLineItem(QLineF(self.initPos, mouseEvent.scenePos()))
            item.setPen( QPen(self.lineColor) )
            item.setFlag(QGraphicsItem.ItemIsMovable, True)
            item.setFlag(QGraphicsItem.ItemIsSelectable, True)
            self.addItem(item)
            #la linea propia podria definirse asi (haría falta definir el metodo paint de UNLine):
            unLine = UNLine(self.initPos, mouseEvent.scenePos())
            unLine.setFlag(QGraphicsItem.ItemIsMovable, True)
            unLine.setFlag(QGraphicsItem.ItemIsSelectable, True)
            self.addItem(unLine)        
        self.flagInteractive = False

class MainWindow(QMainWindow):
    def __init__(self):
        """
        main window object
        """
        QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.setWindowTitle("Primitives-2D")
        # Connect actions
        #QMetaObject.connectSlotsByName(self) #connect slotsbyname triggers several times (3) the action!
        #the slot definition would be something like this: def on_openAction_triggered(self):
        self.connect(self.ui.exitAction, SIGNAL("triggered()"), self.close)
        self.connect(self.ui.openAction, SIGNAL("triggered()"), self.open)
        #create the scene and connect it with the view
        self.simpleScene = SimpleScene()
        self.ui.sceneMenu.addAction(self.simpleScene.lineColorAction)
        self.view = QGraphicsView(self.simpleScene, self)
        self.view.setRenderHint(QPainter.Antialiasing)
        self.view.setObjectName(QString.fromUtf8("vie"))
        self.setCentralWidget(self.view)

    def open(self):
        fileName = QFileDialog.getOpenFileName(self, "Choose a model to open")
        self.statusBar().showMessage("File loaded", 2000)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())